<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert show-icon title="注意：只允许为第三级分类设置相关参数" type="warning" :closable="false"></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <span>选择商品分类：</span>
        <!-- 选择商品分类级联选择框 -->
        <el-cascader expand-trigger="hover" v-model="selectedCateKeys" :options="cateList" :props="cateProps"
          @change="handleChange">
        </el-cascader>
        <!-- tabs标签页 -->
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="showAddDialog">添加参数</el-button>
            <!-- 动态参数表格 -->
            <el-table :data="manyTableData" border stripe>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable
                    @close="handleClose(index,scope.row)">
                    {{item}}</el-tag>
                  <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                    ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)">
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column type="index">
              </el-table-column>
              <el-table-column prop="attr_name" label="参数名称">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">
                    编辑</el-button>
                  <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="only">
            <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="showAddDialog">添加属性</el-button>
            <!-- 静态属性表格 -->
            <el-table :data="onlyTableData" border stripe>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable
                    @close="handleClose(index,scope.row)">{{item}}</el-tag>
                  <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                    ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)">
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column type="index">
              </el-table-column>
              <el-table-column prop="attr_name" label="属性名称">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">
                    编辑</el-button>
                  <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-row>
    </el-card>
    <!-- 添加参数/属性对话框 -->
    <el-dialog :title="'添加' + addDialogtitleText" :visible.sync="addDialogVisible" width="50%"
      @closed="addDialogClosed">
      <!-- 表单区域 -->
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px">
        <el-form-item :label="addDialogtitleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog :title="'修改' + addDialogtitleText" :visible.sync="editDialogVisible" width="50%"
      @close="editDialogClosed">
      <!-- 表单区域 -->
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="100px">
        <el-form-item :label="addDialogtitleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams(editForm.attr_id)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        // 商品分类数据
        cateList: [],
        // 级联选择框的配置对象
        cateProps: {
          value: 'cat_id',
          label: 'cat_name',
          children: 'children'
        },
        // 级联选择框双向绑定的数组
        selectedCateKeys: [],
        // 被选中标签页的名称
        activeName: 'many',
        // 动态参数数据
        manyTableData: [],
        // 静态属性数据
        onlyTableData: [],
        // 控制添加参数/属性对话框的显示
        addDialogVisible: false,
        // 添加按钮的表单数据对象
        addForm: {
          attr_name: ''
        },
        // 添加表单的验证规则
        addFormRules: {
          attr_name: [
            { required: true, message: '请输入参数名称', trigger: 'blur' }
          ]
        },
        // 编辑按钮的表单数据对象
        editForm: {
          attr_name: ''
        },
        // 控制编辑对话框的显示
        editDialogVisible: false,
        // 编辑表单的验证规则
        editFormRules: {
          attr_name: [
            { required: true, message: '请输入参数名称', trigger: 'blur' }
          ]
        }
      };
    },
    created() {
      this.getCateList();
    },
    methods: {
      async getCateList() {
        const { data: res } = await this.$axios.get('categories');
        if (res.meta.status !== 200) {
          return this.$message.error('获取商品分类失败');
        }
        this.cateList = res.data;
      },
      // 级联选择框选项变化时触发
      async handleChange() {
        this.getParamsData();
      },
      // 获取参数列表数据
      async getParamsData() {
        if (this.selectedCateKeys.length !== 3) {
          this.selectedCateKeys = [];
          this.manyTableData = [];
          this.onlyTableData = [];
          return;
        }
        // console.log(this.selectedCateKeys);
        const { data: res } = await this.$axios.get('categories/' + this.cateId + '/attributes', {
          params: { sel: this.activeName }
        });
        if (res.meta.status !== 200) {
          return this.$message.error('获取参数失败');
        }
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
          item.inputVisible = false;
          item.inputValue = '';
        });
        if (this.activeName === 'many') {
          this.manyTableData = res.data;
        } else {
          this.onlyTableData = res.data;
        }
      },
      // tabs标签页点击事件
      handleTabClick() {
        this.getParamsData();
      },
      // 点击添加按钮弹出对话框
      showAddDialog() {
        this.addDialogVisible = true;
      },
      // 关闭添加参数/属性对话框触发
      addDialogClosed() {
        this.$refs.addFormRef.resetFields();
      },
      // 添加参数/属性
      addParams() {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) return;
          const { data: res } = await this.$axios.post('categories/' + this.cateId + '/attributes', {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          });
          if (res.meta.status !== 201) {
            return this.$message.error('添加失败');
          }
          this.$message.success('添加成功');
          this.addDialogVisible = false;
          this.getParamsData();
        });
      },
      // 编辑对话框弹出
      async showEditDialog(id) {
        const { data: res } = await this.$axios.get('categories/' + this.cateId + '/attributes/' + id, {
          params: { attr_sel: this.activeName }
        });
        if (res.meta.status !== 200) {
          return this.$message.error('获取参数信息失败');
        }
        this.editForm = res.data;
        this.editDialogVisible = true;
      },
      // 关闭编辑对话框触发
      editDialogClosed() {
        this.$refs.editFormRef.resetFields();
      },
      // 编辑对话框的确定按钮
      editParams(id) {
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) {
            return;
          }
          const { data: res } = await this.$axios.put('categories/' + this.cateId + '/attributes/' + id, {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          });
          if (res.meta.status !== 200) {
            return this.$message.error('修改失败');
          }
          this.$message.success('修改成功');
          this.getParamsData();
          this.editDialogVisible = false;
        });
      },
      // 删除参数/属性
      removeParams(id) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const { data: res } = await this.$axios.delete('categories/' + this.cateId + '/attributes/' + id);
          if (res.meta.status !== 200) {
            return this.$message.error('删除参数失败');
          }
          this.getParamsData();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // 文本框失去焦点或按下回车键时触发
      async handleInputConfirm(row) {
        if (row.inputValue.trim().length === 0) {
          row.inputValue = '';
          row.inputVisible = false;
          return;
        }
        row.attr_vals.push(row.inputValue.trim());
        row.inputValue = '';
        row.inputVisible = false;
        this.saveAttrVals();
      },
      // 点击按钮展示文本输入框
      showInput(row) {
        row.inputVisible = true;
        // 使文本框自动获得焦点
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      // 对参数的操作保存进数据库
      async saveAttrVals(row) {
        const { data: res } = await this.$axios.put('categories/' + this.cateId + '/attributes/' + row.attr_id, {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        });
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数项失败');
        }
        this.$message.success('修改参数项成功');
      },
      // 删除对应的参数可选项
      handleClose(i, row) {
        row.attr_vals.splice(i, 1);
        this.saveAttrVals(row);
      }
    },
    computed: {
      // 添加按钮是否禁用
      isBtnDisabled() {
        if (this.selectedCateKeys.length !== 3) {
          return true;
        }
        return false;
      },
      // 当前选中的三级分类id
      cateId() {
        if (this.selectedCateKeys.length === 3) {
          return this.selectedCateKeys[2];
        }
        return null;
      },
      // 添加对话框的标题文本
      addDialogtitleText() {
        if (this.activeName === 'many') {
          return '动态参数';
        }
        else {
          return '静态属性';
        }
      }
    }
  };
</script>
<style lang="scss" scoped>
  .cat_opt {
    margin: 15px 0;
  }

  .el-tag {
    margin: 10px;
  }

  .input-new-tag {
    width: 120px;
  }
</style>
